package com.bupt.websocket.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.stream.Stream;

import com.bupt.websocket.service.StorageService;

@Service
public class FileSystemStorageService implements StorageService {

    private final Path rootLocation;
    private final String proper_path;
    private final String nginx_path;

    @Autowired
    public FileSystemStorageService(StorageProperties properties) {
        this.rootLocation = Paths.get(properties.getLocation());
        this.proper_path = properties.getLocation();
        this.nginx_path = properties.getNginxLocation();
    }

    @Override
    public String store(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        if(originalFilename.equals("")||originalFilename==null){
            originalFilename = file.getName();
        }
        String extName = originalFilename.substring(originalFilename.indexOf("."));
        UUID uuid = UUID.randomUUID();
        String filename = StringUtils.cleanPath(uuid+extName);

        Calendar instance = Calendar.getInstance();
        String year = String.valueOf(instance.get(Calendar.YEAR));
        String month = String.valueOf(instance.get(Calendar.MONTH));
        String day = String.valueOf(instance.get(Calendar.DATE));

        String date_path = "/"+year+"/"+month+"/"+day;

        //D:开头的地址；
        String final_path = proper_path + date_path;

        //保证有目录；
        boolean b = Files.notExists(Paths.get(final_path));
        try {
            Files.createDirectories(Paths.get(final_path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //尝试上传；
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file " + filename);
            }
            if (filename.contains("..")) {
                // This is a security check
                throw new StorageException(
                        "Cannot store file with relative path outside current directory "
                                + filename);
            }

            Files.copy(file.getInputStream(), Paths.get(proper_path + date_path+"/"+filename),StandardCopyOption.REPLACE_EXISTING);
        }
        catch (IOException e) {
            throw new StorageException("Failed to store file " + filename, e);
       }

       return nginx_path + date_path + "/" + filename;
    }

    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(path -> this.rootLocation.relativize(path));
        }
        catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

    @Override
    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            }
            else {
                throw new StorageFileNotFoundException(
                        "Could not read file: " + filename);

            }
        }
        catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("Could not read file: " + filename, e);
        }
    }

    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public void init() {
        try {
            Files.createDirectories(rootLocation);
        }
        catch (IOException e) {
            throw new StorageException("Could not initialize storage", e);
        }
    }
}
